<template>
  <div class="app-container">
    <!-- 条件查询   -->
    <el-form :inline="true" :model="searchParam" size="mini" >
      <el-form-item label="标题关键字:">
        <el-input v-model.trim="searchParam.title" placeholder="请输入标题关键字" clearable></el-input>
      </el-form-item>
      <el-form-item label="作者名称:">
        <el-input v-model.trim="searchParam.authorName" placeholder="请输入作者名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="分类:">
        <el-select v-model="checkedCategoryId" clearable filterable style="width:120px;" placeholder="请选择分类">
          <el-option :label="item.categoryName" :value="item.categoryId"
                     v-for="(item, index) in categoryList" :key="item.categoryId" />
        </el-select>
      </el-form-item>
      <el-form-item label="标签:">
        <el-select v-model="searchParam.labelId" clearable filterable style="width:120px;" placeholder="请选择标签">
          <el-option :label="item.labelName" :value="item.labelId"
                     v-for="(item, index) in labelList" :key="item.labelId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="searchParam.status" clearable filterable style="width:120px;" placeholder="请选择">
          <el-option label = "草稿中" :value = 1 />
          <el-option label = "待发布" :value = 2  />
          <el-option label = "已发布" :value = 3  />
        </el-select>
      </el-form-item>
      <el-form-item label="范围:">
        <el-select v-model="searchParam.scope" clearable filterable style="width:120px;" placeholder="请选择">
          <el-option label="全部" value="all"></el-option>
          <el-option label="只看自己" value="self"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item >
        <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reload">重置</el-button>
        <el-button :icon="advanceSearch === false ? 'el-icon-arrow-down' : 'el-icon-arrow-up'  "
                   type="info" @click="advanceSearch = !advanceSearch">高级搜索</el-button>
      </el-form-item>

      <!--  高级搜索    -->
      <div v-show="advanceSearch">
        <el-form-item label="文章类型:">
          <el-select v-model="searchParam.articleType" clearable filterable style="width:120px;" placeholder="请选择">
            <el-option label = "原创" :value = 1 />
            <el-option label = "转载" :value = 2  />
          </el-select>
        </el-form-item>
        <el-form-item label="公开类型:">
          <el-select v-model="searchParam.publicType" clearable filterable style="width:120px;" placeholder="请选择">
            <el-option label = "仅自己可见" :value = 1 />
            <el-option label = "所有人可见" :value = 3  />
          </el-select>
        </el-form-item>
        <el-form-item label="是否定时发布:">
          <el-select v-model="searchParam.timedRelease" clearable filterable style="width:120px;" placeholder="请选择">
            <el-option label = "否" :value = 0 />
            <el-option label = "是" :value = 1  />
          </el-select>
        </el-form-item>
        <el-form-item label="审批状态:">
          <el-select v-model="searchParam.approveStatus" clearable filterable style="width:120px;" placeholder="请选择">
            <el-option label = "待审批" :value = 1 />
            <el-option label = "审批通过" :value = 2  />
            <el-option label = "审批拒绝" :value = 3  />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间:">
          <el-date-picker
            v-model="searchParam.createTimeRange"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right">
          </el-date-picker>
        </el-form-item>
      </div>


    </el-form>


    <!--  列表数据  -->
    <el-table :data="list" border style="width: 100%">
      <el-table-column align="center" label="序号" width="50" type="index"></el-table-column>
      <el-table-column align="center" prop="cover" label="封面图" width="80">
        <template slot-scope="scope">
          <el-image :src="scope.row.cover"
                    :preview-src-list = "[scope.row.cover]"
                    style="height: 50px;width: 50px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="title" label="文章标题" width="260" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="summary" label="文章摘要" width="260" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="authorName" label="作者" width="100" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="categoryName" label="分类" width="110">
        <template slot-scope="scope">
          <el-tag>{{scope.row.categoryName}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="labelName" label="标签" width="110">
        <template slot-scope="scope">
          <el-tag type="info">{{scope.row.labelName}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="status" label="状态" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 3" type="success">已发布</el-tag>
          <el-tag v-if="scope.row.status === 1" type="danger">草稿中</el-tag>
          <el-tag v-if="scope.row.status === 2" type="warning">待发布</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="publicType" label="公开类型" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.publicType === 1" type="danger">仅自己可见</el-tag>
          <el-tag v-if="scope.row.publicType === 2" type="warning">组织内成员可见</el-tag>
          <el-tag v-if="scope.row.publicType === 3" type="success">所有人可见</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="articleType" label="文章类型" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.articleType === 1" type="danger">原创</el-tag>
          <el-tag v-if="scope.row.articleType === 2" type="warning">转载</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="allowComment" label="是否允许评论" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.allowComment === 1" type="danger">允许</el-tag>
          <el-tag v-if="scope.row.allowComment === 0" type="warning">不允许</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="timedRelease" label="是否定时发布" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.timedRelease === 1" type="info">是</el-tag>
          <el-tag v-if="scope.row.timedRelease === 0" type="info">否</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="cronReleaseTime" label="定时发布时间" width="160">
        <template slot-scope="scope">
          {{ getFormat(scope.row.cronReleaseTime) }}
        </template>
      </el-table-column>

      <el-table-column align="center" prop="autoPublish" label="是否自动发布" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.autoPublish === 1" type="info">是</el-tag>
          <el-tag v-if="scope.row.autoPublish === 0" type="info">否</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="views" label="浏览数" width="80">
        <template slot-scope="scope">
          <el-tag type="primary">{{scope.row.views}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="likes" label="点赞数" width="80" >
        <template slot-scope="scope">
          <el-tag type="primary">{{scope.row.likes}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="approveStatus" label="审批状态" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.approveStatus === 1" type="success">待审批</el-tag>
          <el-tag v-if="scope.row.approveStatus === 2" type="danger">审批通过</el-tag>
          <el-tag v-if="scope.row.approveStatus === 3" type="warning">审批拒绝</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="approveTime" label="审批时间" width="160">
        <template slot-scope="scope">
          {{ getFormat(scope.row.approveTime) }}
        </template>
      </el-table-column>


      <el-table-column align="center" prop="updateTime" label="更新时间" width="160">
        <template slot-scope="scope">
          {{ getFormat(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间" width="160">
        <template slot-scope="scope">
          {{ getFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column  align="center" label="操作" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button icon="el-icon-search" type="primary" size="mini" @click="detail(scope.row.articleId)">查看</el-button>
          <el-button icon="el-icon-document-delete" type="danger" size="mini" @click="handleDel(scope.row.articleId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 10px;">
      <el-pagination background
           @size-change="handleSizeChange"
           @current-change="handleCurrentChange"
           :current-page="searchParam.pageNo"
           :page-sizes="[10, 20, 100]"
           :page-size="searchParam.pageSize"
           layout="total, sizes, prev, pager, next, jumper"
           :total="searchParam.total">
    </el-pagination>
    </div>

    <el-dialog title="文章详情" :visible.sync="detailVisible" width="60%" before-close="" :close-on-click-modal="false">
      <el-form ref="formData" :model="articleDetail" label-width="100px"  >
        <el-form-item label="标题:">
          <el-input v-model="articleDetail.title"></el-input>
        </el-form-item>
        <el-form-item label="摘要:">
          <el-input type="textarea" v-model="articleDetail.summary"></el-input>
        </el-form-item>
        <el-form-item label="作者:">
          <el-input v-model="articleDetail.authorName"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <mavonEditor v-model="articleDetail.mdContent" />
        </el-form-item>
        <el-form-item align="center">
          <el-button type="danger"  @click="detailVisible = false">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { dateFormat } from '@/utils/date';
import { articleList,  deleteArticle, articleDetail } from '@/api/article';
import { listCategory } from '@/api/category';
import { listByCategoryId } from '@/api/label';
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';

export default {
  components:{
    mavonEditor
  },
  data() {
    return {
      advanceSearch: false,
      articleDetail: {},
      detailVisible: false,
      list: [],
      query: {
        current: 1,   // 当前页码
        size: 10,     // 每页大小
        total: 0,
        title: "",
        authorName: ""
      },
      checkedCategoryId: '',  // 选中的分类
      checkedStatusId: '',  // 选中的状态
      edit:{
        title: '',
        visiable: false,
        isEdit: true,
        id: null,
      },
      categoryList: [],
      labelList: [],
      scope: "all",
      searchParam: {
        pageNo: 1,
        pageSize: 10,
        status: '',
        total: 0,
        title: '',
        categoryId: '',
        labelId: '',
        scope: 'all',
        authorName: '',
        publicType: '',
        articleType: '',
        timedRelease: '',
        approveStatus: '',
        createTimeRange: []
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },

  created() {
    this.fetchData();
    this.fetchCategoryList();
  },

  methods: {
    // 条件分页查询博客列表
    fetchData() {
      this.searchParam.categoryId = this.checkedCategoryId;
      articleList(this.searchParam).then(res => {
        const { code, data, message } = res;
        if (code === 200) {
          this.list = data.list;
          this.searchParam.total = data.total;
        } else {
          this.$notify.error({
            title: '错误',
            message: message,
            duration: 1500
          });
        }
      })
    },

    // 根据分类ID获取标签信息
    fetchLabelListByCategory(categoryId) {
      listByCategoryId(categoryId).then(res => {
        const { code, data, message } = res;
        if (code === 200) {
          this.labelList = data;
        } else {
          this.$notify.error({
            title: '错误',
            message: message,
            duration: 1500
          });
        }
      })
    },

    fetchCategoryList() {
      listCategory().then(res => {
        const { code, data, message } = res;
        if (code === 200) {
          this.categoryList = data.list;
        } else {
          this.$notify.error({
            title: '错误',
            message: message,
            duration: 1500
          });
        }
      })
    },

    // 查询文章详情
    detail(id) {
      articleDetail(id).then(res => {
        const { code, data, message } = res;
        if (code === 200) {
          this.articleDetail = data;
          this.detailVisible = true;
        } else {
          this.$notify.error({
            title: '错误',
            message: message,
            duration: 1500
          });
        }
      })
    },

    // 条件查询
    queryData() {
      this.query.categoryId = this.checkedCategoryId;
      this.fetchData();
    },

    // val 是切换之后的每页显示多少条
    handleSizeChange(val) {
      this.searchParam.pageSize = val;
      this.fetchData();
    },

    // 当页码改变后触发此方法 val是当前点击（或输入）的页码
    handleCurrentChange(val) {
      this.searchParam.pageNo = val;
      this.fetchData();
    },

    // 删除
    handleDel(id) {
      this.$confirm('确认删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        deleteArticle(id).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else if (response.code === 403) {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: '系统异常，请稍后再试',
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchData();
        })
      }).catch(() => {
        // 取消删除
      });
    },

    // 重置
    reload(){
      this.searchParam.pageSize = 10;
      this.searchParam.pageNo = 1;
      this.searchParam.total = 0;
      this.searchParam.title = '';
      this.searchParam.status = '';
      this.searchParam.scope = 'all';
      this.searchParam.categoryId = '';
      this.searchParam.labelId = '';
      this.checkedCategoryId = '';
      this.checkedStatusId = '';
      this.searchParam.authorName = '';
      this.searchParam.articleType = '';
      this.searchParam.publicType = '';
      this.searchParam.approveStatus = '';
      this.searchParam.timedRelease = '';
      this.searchParam.createTimeRange = [];
      this.checkedCategoryId = '';
      this.fetchData();
    },

    // 格式化日期
    getFormat(date){
      if (!date) {
        return date;
      }
      return dateFormat(date);
    },

  },

  watch: {
    checkedCategoryId(val) {
      if (val) {
        this.fetchLabelListByCategory(val);
      } else {
        this.searchParam.labelId = '';
      }
    }
  }
}
</script>

<style scoped>
.showInline {
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap
}
</style>
